import {loginApi, type LoginParams} from "@/api/user"
import router from "@/router"
import {constRouter} from "@/router/route"
import {removeToken, setToken} from "@/utils/local"
import {defineStore} from "pinia"
import {ref} from "vue"
import type {RouteLocationOptions} from "vue-router"

export const useUserStore = defineStore(
    "user",
    () => {
        /***
         * @登录
         */
        const userinfo = ref(<any>{})
        // 用户登录
        const login = async (loginParams: LoginParams) => {
            const res = await loginApi(loginParams)
            console.log(res)
            if (res.code === 200) {
                setToken(res.data.token)
                return res.data
            } else {
                return Promise.reject(new Error(res.message))
            }
        }
        /**
         * @路由
         */

            // 路由表
        const routerMenuList = ref(constRouter as RouteLocationOptions[])
        // // 权限路过滤
        const filterRoute = (routes: any, asyncRoute: any) => {
            return asyncRoute.filter((route: any) => {
                if (routes.includes(route.name)) {
                    if (route.children && route.children.length > 0) {
                        route.children = filterRoute(routes, route.children)
                    }
                    return true
                }
            })
        }
        // 获取用户信息
        // 所有异步路由
        // 重置路由
        const resetRoutes = () => {
            //移除所有路由
            routerMenuList.value.forEach((route: any) => {
                router.removeRoute(route.name)
            })
        }

        // 退出登录
        const loginOut = () => {
            removeToken()
            userinfo.value = {}
            routerMenuList.value = []
            resetRoutes()
        }

        return {
            routerMenuList,
            userinfo,
            loginUp: login,
            loginOut,
            resetRoutes,
        }
    },
)
